package com.jxj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxj.dao.AdminUserMapper;
import com.jxj.dao.OrgMapper;
import com.jxj.dao.SocResumeMsgMapper;
import com.jxj.dao.UserMapper;
import com.jxj.entity.ResumeVO;
import com.jxj.entity.UserResumeVO;
import com.jxj.entity.gen.Adminuser;
import com.jxj.entity.gen.TUser;
import com.jxj.service.UserService;
import com.jxj.util.DOCUtil;
import com.jxj.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Cambria
 * @creat 2021/8/15 11:35
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper , TUser> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private OrgMapper orgMapper;
    @Resource
    AdminUserMapper adminUserMapper;
    @Autowired
    SocResumeMsgMapper socResumeMsgMapper;

    private static final String APPID = "wx20e548c42b580824";
    private static final String APPSECRET = "9b6f84ef12d8b3eabca4b8ec1931673e";
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "$secret=" + APPSECRET + "&grant_type=authorization_code&js_code=";

    @Override
    public List<UserResumeVO> selectAllResumeByUid(Serializable uid) {
        List<UserResumeVO> userResumeVOS = userMapper.selectAllResumeByUid(uid);
        return userResumeVOS;
    }

    @Override
    public String register(String code) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        JSONObject json = null;
        String token = null;

        List<BasicNameValuePair> param = new ArrayList<>();
        log.debug("\n------\nuser {} login\n------\n" , code);
        param.add(new BasicNameValuePair("js_code" , code));
        param.add(new BasicNameValuePair("appid" , APPID));
        param.add(new BasicNameValuePair("secret" , APPSECRET));
        param.add(new BasicNameValuePair("grant_type", "authorization_code"));

        try {

            HttpPost httpPost = new HttpPost(URL+code);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            response = client.execute(httpPost);

            json = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));

            TUser user = userMapper.selectByOpenId(json.getString("openid"));

            if (user == null) {

                user = new TUser();
                user.setOpenId(json.getString("openid"));
                user.setSessionKey(json.getString("session_key"));
                user.setOid(-1);

                userMapper.insert(user);
            }

            token = JWTUtil.sign(user);

        } catch (Exception e) {

            log.info("{}登陆失败" , code);
            e.printStackTrace();

        } finally {

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return token;
        }
    }

    @Override
    public File resumeParseDoc(ResumeVO resume) {
        socResumeMsgMapper.insert(resume);

        return DOCUtil.resumeParseDoc(resume);
    }

    @Override
    public JSONObject adminRegister(Adminuser admin) {
        log.info("\n------\nadmin login {}\n------\n" , admin);
        QueryWrapper<Adminuser> wrapper = new QueryWrapper<>();
        wrapper.eq("accout" , admin.getAccout()).eq("password" , admin.getPassword());
        Adminuser user = adminUserMapper.selectOne(wrapper);
        JSONObject json = new JSONObject();
        if (user == null) {
            json.put("json" , null);
            json.put("类别" , null);
        } else {
            log.info("info:{}" , user);
            String token = JWTUtil.sign(user);
            json.put("token" , token);
            log.info("\n------\ntoken {}\n------\n" , token);
//        json.put("类别" , orgMapper.selectOrgClass1ById(user.getOid()));
            json.put("类别" , user.getClass_one());
        }
        return json;
    }
}
